
*******************************************************
*******************************************************
*************** THIS IS DO FILE 10 ********************
******** THIS FILE RUNS THE X-STATE REGRESSIONS *******
*******************************************************
*******************************************************

*Version: 2023 March 29


cap mkdir `"$output/paper_inputs"'
cap mkdir `"$output/log/10_regression_analysis"'
cap mkdir `"$output/regression_analysis"'
cap mkdir `"$output/regression_analysis/cross_state"'

cap log close 
log using `"$output/log/10_regression_analysis/10_regression_analysis_cross_state.smcl"', replace 

di "This run uses code version from 2023/03/29"


use `"$raw_input/$x_state_file_regression"', clear


bys payee_state_cd: gegen mean_accept = mean(acceptinsurance)
bys payee_state_cd: gen observations = _N 
bys payee_state_cd: keep if _n == 1 
keep payee_state_cd mean_accept observations

save `"$output/regression_analysis/cross_state/state_accept.dta"', replace 


use `"$raw_input/$x_state_file_regression"', clear

//generate Medicare accept 
gen accept_medicare = 1 if medicare == "Y"
replace accept_medicare = 0 if medicare == "N"
replace accept_medicare = . if acceptinsurance == . 
bys npimedicare_id: gegen mean_medicare = mean(accept_medicare)
gen capacity = 1 - mean_medicare

*merge in the indices 
merge m:1 payee_state_cd using `"$indices/fee_indices_medicaid.dta"', keepusing(pi*)
keep if _merge == 3
drop _merge 

merge m:1 payee_state_cd using `"$indices/CIP_indices_medicaid.dta"', keepusing(*CIP*)
keep if _merge == 3
drop _merge 


//merge controls 
merge m:1 year FIPS using `"$control_var/county_controls.dta"'
keep if _merge == 3 // all data from master file merge 
drop _merge 

destring statefips, replace  
merge m:1 year statefips using `"$control_var/control_vars_state.dta"'
keep if _merge == 3 //all data from the master file merge 
drop _merge 

eststo clear 
cd `"$output/regression_analysis/cross_state"'
estpost tabstat acceptinsurance, stat(mean sd p10 p90 n) columns(statistics) 

#delimit ;
		esttab using `"accept_statistics.tex"', cells("mean(fmt(3)) sd(fmt(2)) p10(fmt(2)) p90(fmt(2)) count(fmt(0))") 
		unstack nonumbers replace substitute(_ \_) 
	    noobs collabels("Mean" "SD" "10th Percentile" "90th Percentile" "Observations");
#delimit cr 


//Use only TIN info to connect groups
gen skaGroup3a=string(ID)
replace skaGroup3a="MDPPASTIN"+tin  if ~missing(tin)

//drop missing
drop if missing(paystateid)

cap drop group?
gegen group3 = group(skaGroup3a)
gegen group3y = group(skaGroup3a year)

//cross state variable 
cap drop totstates?	
sort year group3 paystateid
by year group3 paystateid: gen markstate=_n==1
by year group3: egen totstates3=sum(markstate)
drop markstate


gen ltotdocsALL1=lnumdocs

gen kaiser=CODE3=="KAI"
drop if kaiser

cap drop MDsPerCapita
gen MDsPerCapita = tot_active_md/county_pop

foreach c of varlist veteran unempl poverty white {
	
	replace `c' = `c'/county_pop
}


unab controllist: mean_ma_pen mean_number_mediciad_elig mean_dual mean_unins65 mean_number_medicare_elig mean_medicare_enrol 
unab year_controllist: hinsva hinscare hinscaid hcovany veteran unempl med_hh_ince avg_hhc county_pop tot_active_md poverty white


**ensure controls are not missing
foreach var of varlist `controllist' `year_controllist' {
	
	keep if `var' != . 
}

unab health_ins_market_year: hinscaid hcovany hinscare avg_hhc mean_ma_pen mean_number_mediciad_elig mean_dual mean_unins65 mean_number_medicare_elig mean_medicare_enrol 
unab health_prov_year: tot_active_md MDsPerCapita
unab ses_year: unempl white county_pop veteran poverty med_hh_ince
	


foreach group of var group3 { 
	
	
	if "`group'" == "group3" {
		local cross_state_var totstates3
		local definition "MDPPAS_Tax_ID"
		local group_table "Tax ID"
	}
	

	xtset `group'
	
	cap drop physind 
	cap drop phys_count
	cap drop group_ind
	gen group_ind = 1 if `cross_state_var'>1 & `group' != . & capacity == 0
	gen physind = 0
	bys npimedicare_id group_ind: replace physind = 1 if _n == 1 
	replace physind = 0 if group_ind != 1
	gegen phys_count = sum(physind)
	local physcount : di %7.0fc phys_count
	di `physcount'
	


	//Cross State Regressions

	local loss_denial v_initial_den_CIP
	local loss lev_CIP_FE
	local loss_heck lev_CIP_FE_nofe
	local fee pi_c_FE_cpt_line
	
	local loss_name `loss' CIP `loss_heck' CIP 
	local fee_name `fee' Fee


	
	//Column 2
	//No selection Correction, Restricted sample IV
	ivreghdfe acceptinsurance `fee' (`loss'=`loss_denial') `health_ins_market_year' `health_prov_year' `ses_year' i.year if `cross_state_var'>1 & capacity == 0, absorb(`group') cluster(paystateid) first
	estadd local pys_number "`physcount'"
	estadd local sel_cor_index "No"
	estadd local phys_fe_index "Yes"
	estadd local instrument "2SLS"
	estadd local group_FE "Yes"
	estadd local controls "Yes"
	estadd local Sample "Yes"
	eststo mainxstate2		
	est save "mainxstate2_`group'.ster", replace

	//Column 1
	// No selection Correction, Restricted sample OLS
	areg acceptinsurance `fee' `loss' `health_ins_market_year' `health_prov_year' `ses_year' i.year if e(sample), absorb(`group') vce(cluster paystateid)
	estadd local pys_number "`physcount'"
	estadd local sel_cor_index "No"
	estadd local phys_fe_index "Yes"
	estadd local instrument "OLS"
	estadd local group_FE "Yes"
	estadd local controls "Yes"
	estadd local Sample "Yes"
	eststo mainxstate1
	est save "mainxstate1_`group'.ster", replace
			
	//Column 3
	// Selection Correction, Restricted sample OLS
	areg acceptinsurance `fee' `loss_heck' `health_ins_market_year' `health_prov_year' `ses_year' i.year if e(sample), absorb(`group') vce(cluster paystateid)
	estadd local pys_number "`physcount'"
	estadd local sel_cor_index "Yes"
	estadd local phys_fe_index "No"
	estadd local instrument "OLS"
	estadd local group_FE "Yes"
	estadd local controls "Yes"
	estadd local Sample "Yes"
	eststo mainxstate3
	est save "mainxstate3_`group'.ster", replace

	//Column 4
	// Selection Correction, Restricted sample IV
	ivreghdfe acceptinsurance `fee' (`loss_heck'=`loss_denial') `health_ins_market_year' `health_prov_year' `ses_year' i.year if e(sample), absorb(`group') cluster(paystateid) first
	estadd local pys_number "`physcount'"
	estadd local sel_cor_index "Yes"
	estadd local phys_fe_index "No"
	estadd local instrument "2SLS"
	estadd local group_FE "Yes"
	estadd local controls "Yes"
	estadd local Sample "Yes"
	eststo mainxstate4	
	est save "mainxstate4_`group'.ster", replace 
	
	
	//First stage corresponding to column 2
	areg `loss' `loss_denial' `fee' `health_ins_market_year' `health_prov_year' `ses_year' i.year  if e(sample) , absorb(`group') cluster(paystateid) 
					
	estadd local pys_number "`physcount'"
	estadd local sel_cor_index "No"
	estadd local phys_fe_index "Yes"
	estadd local group_FE "Yes"
	estadd local controls "Yes"
	estadd local Sample "Yes"
	eststo mainxstateFS2
	est save "mainxstateFS2_`group'.ster", replace
	
	//First stage corresponding to column 4
	areg `loss_heck' `loss_denial' `fee' `health_ins_market_year' `health_prov_year' `ses_year' i.year  if e(sample) , absorb(`group') cluster(paystateid) 
					
	estadd local pys_number "`physcount'"
	estadd local sel_cor_index "Yes"
	estadd local phys_fe_index "No"
	estadd local group_FE "Yes"
	estadd local controls "Yes"
	estadd local Sample "Yes"
	eststo mainxstateFS4	
	est save "mainxstateFS4_`group'.ster", replace

	// set output dir to avoid conflict on BEA server
	
	cd "..\..\..\..\code\main_article\"
	cd `"$output/paper_inputs"'
	#delimit ;

		//cross state table
		esttab mainxstate1 mainxstate2 mainxstate3 mainxstate4 using `"`group'_main.tex"' ,  replace substitute(_ \_)
		numbers  nomtitles booktabs mgroups("Accept Medicaid Patients?", pattern(1 0 0 0) prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span}))
		rename(`loss_name' `fee_name')
		keep(Fee CIP ) 
		order(CIP Fee)
		coeflabels(Fee "$\log \pi$ index"
			   CIP "$\tau$ index"
	)
		se b(4) se(4 ) stats(instrument Sample pys_number N group_FE controls phys_fe_index  sel_cor_index , fmt(%7.0fc %9.0fc) labels("\footnotesize{Estimator}" "\footnotesize{Subsample Accepting Medicare}" "\footnotesize{N.~Physicians}" "\footnotesize{N.~Physicians-Years}" "\footnotesize{Group FE}" "\footnotesize{Controls}"  "\midrule  $\tau$ index: \\ \multicolumn{1}{r}{\footnotesize{Physician FE}}" "\multicolumn{1}{r}{\footnotesize{Selection Correction}}" ))
	starlevels(* 0.10 ** 0.05 *** 0.01)  label varwidth(20) nonotes;
	
	
	
		//first stage table 
		esttab mainxstateFS2 mainxstateFS4 using `"`group'_main_FS.tex"',  replace substitute(_ \_)
		numbers  nomtitles booktabs mgroups("$\tau$ index", pattern(1 0) prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span}))
		keep(`loss_denial' `fee') 
		coeflabels(`loss_denial' "Denial rate index"
					`fee' "$\log \pi$ index"

		)
		se b(4) se(4 ) stats(Sample pys_number N group_FE controls phys_fe_index  sel_cor_index , fmt(%7.0fc %9.0fc) labels("\footnotesize{Subsample Accepting Medicare}" "\footnotesize{N.~Physicians}" "\footnotesize{N.~Physicians-Years}" "\footnotesize{Group FE}" "\footnotesize{Controls}"  "\midrule  $\tau$ index: \\ \multicolumn{1}{r}{\footnotesize{Physician FE}}" "\multicolumn{1}{r}{\footnotesize{Selection Correction}}" ))
	starlevels(* 0.10 ** 0.05 *** 0.01)  label varwidth(20) nonotes;

					
	#delimit cr

	
	
}


cd "..\..\..\code\main_article\"

